<template>
  <div class="order-management-container">
    <!-- 页面标题 -->
<!--    <div class="page-header">-->
<!--      <h2 class="page-title">订单管理</h2>-->
<!--    </div>-->

    <!-- 查询表单 -->
    <el-card class="query-form-card">
      <el-form :model="queryForm" inline label-width="80px" class="query-form">
        <!-- 订单ID -->
        <el-form-item label="订单ID">
          <el-input
              v-model="queryForm.orderId"
              placeholder="请输入订单ID"
              clearable
              size="small"
              class="query-input"
          ></el-input>
        </el-form-item>

        <!-- 用户姓名 -->
        <el-form-item label="用户姓名">
          <el-input
              v-model="queryForm.realName"
              placeholder="请输入用户姓名"
              clearable
              size="small"
              class="query-input"
          ></el-input>
        </el-form-item>

        <!-- 商家名称 -->
        <el-form-item label="商家名称">
          <el-input
              v-model="queryForm.merchantName"
              placeholder="请输入商家名称"
              clearable
              size="small"
              class="query-input"
          ></el-input>
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button
              type="primary"
              size="small"
              @click="handleQuery"
              class="query-btn"
          >
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button
              size="small"
              @click="resetQuery"
              class="reset-btn"
          >
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 订单卡片列表 -->
    <div class="order-cards-container">
      <!-- 加载状态 -->
      <el-skeleton
          v-if="loading"
          :count="pagination.pageSize"
          :rows="5"
          animated
          class="order-skeleton"
      ></el-skeleton>

      <!-- 空状态 -->
      <el-empty
          v-if="!loading && orderList.length === 0"
          description="暂无符合条件的订单"
          class="empty-state"
      ></el-empty>

      <!-- 订单卡片 -->
      <el-card
          v-for="(order, index) in orderList"
          :key="order.id || index"
          class="order-card"
          shadow="hover"
      >
        <!-- 订单头部：ID和状态 -->
        <div class="order-header">
          <div class="order-id">
            <el-icon class="id-icon"><Document /></el-icon>
            订单ID: <span class="id-value">{{ order.id }}</span>
          </div>
          <el-tag
              :type="statusConfig[order.status]?.type"
              size="medium"
              class="order-status"
          >
            {{ statusConfig[order.status]?.label }}
          </el-tag>
        </div>

        <!-- 订单内容 -->
        <div class="order-content">
          <div class="info-grid">
            <!-- 用户信息 -->
            <div class="info-card user-info">
              <div class="info-header">
                <el-icon class="info-icon"><User /></el-icon>
                <span class="info-title">用户信息</span>
              </div>
              <div class="info-detail">
                <div class="detail-item">姓名: {{ order.realName || '--' }}</div>
                <div class="detail-item">账号: {{ order.userUsername || '--' }}</div>
                <div class="detail-item">ID: {{ order.userId || '--' }}</div>
              </div>
            </div>

            <!-- 商家信息 -->
            <div class="info-card merchant-info">
              <div class="info-header">
                <el-icon class="info-icon"><Shop /></el-icon>
                <span class="info-title">商家信息</span>
              </div>
              <div class="info-detail">
                <div class="detail-item">名称: {{ order.merchantName || '--' }}</div>
                <div class="detail-item">ID: {{ order.merchantId || '--' }}</div>
              </div>
            </div>

            <!-- 车辆信息 -->
            <div class="info-card car-info">
              <div class="info-header">
                <el-icon class="info-icon"><DocumentCopy /></el-icon>
                <span class="info-title">车辆信息</span>
              </div>
              <div class="info-detail">
                <div class="detail-item">车辆ID: {{ order.carId || '--' }}</div>
                <div class="detail-item">日租金: ¥{{ order.dailyRent || '0.00' }}</div>
                <div class="detail-item">租期: {{ order.rentDays || 0 }}天</div>
              </div>
            </div>

            <!-- 时间信息 -->
            <div class="info-card time-info">
              <div class="info-header">
                <el-icon class="info-icon"><Clock /></el-icon>
                <span class="info-title">租赁时间</span>
              </div>
              <div class="info-detail">
                <div class="detail-item">预计: {{ formatDate(order.startTime) }} 至 {{ formatDate(order.endTime) }}</div>
                <div v-if="order.actualStartTime" class="detail-item">
                  实际: {{ formatDate(order.actualStartTime) }}
                  <template v-if="order.actualEndTime">
                    至 {{ formatDate(order.actualEndTime) }}
                  </template>
                </div>
              </div>
            </div>

            <!-- 金额信息 -->
            <div class="info-card amount-info">
              <div class="info-header">
                <el-icon class="info-icon"><Money /></el-icon>
                <span class="info-title">金额信息</span>
              </div>
              <div class="info-detail">
                <div class="detail-item">预估: ¥{{ order.estimatedTotalAmount || '0.00' }}</div>
                <div v-if="order.finalAmount" class="detail-item final-amount-item">
                  最终: <span class="final-amount">¥{{ order.finalAmount }}</span>
                </div>
<!--                <div v-if="order.damageFee && order.damageFee > 0" class="detail-item damage-fee-item">-->
<!--                  损坏费: <span class="damage-fee">¥{{ order.damageFee }}</span>-->
<!--                </div>-->
<!--                <div v-if="order.overtimeFee && order.overtimeFee > 0" class="detail-item overtime-fee-item">-->
<!--                  超时费: <span class="overtime-fee">¥{{ order.overtimeFee }}</span>-->
<!--                </div>-->
              </div>
            </div>
          </div>
        </div>

        <!-- 订单操作 -->
        <div class="order-actions">
          <el-button
              type="primary"
              size="small"
              @click="handleEditStatus(order)"
              v-if="canEditStatus(order.status)"
              class="edit-btn"
          >
            <el-icon class="btn-icon"><Edit /></el-icon>
            修改状态
          </el-button>
          <el-button
              type="danger"
              size="small"
              @click="handleDelete(order.id)"
              class="delete-btn"
          >
            <el-icon class="btn-icon"><Delete /></el-icon>
            删除
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          :current-page="pagination.pageNo"
          :page-sizes="[5, 10, 20]"
          :page-size="pagination.pageSize"
          :total="pagination.count"
          :total-pages="pagination.totalPage"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="pagination"
      ></el-pagination>
    </div>

    <!-- 修改状态弹窗 -->
    <el-dialog
        title="修改订单状态"
        v-model="statusDialogVisible"
        width="300px"
        :close-on-click-modal="false"
        destroy-on-close
    >
      <el-form :model="currentOrder" label-width="80px" class="status-form">
        <el-form-item label="当前状态">
          <el-tag
              :type="statusConfig[currentOrder.status]?.type"
              size="small"
          >
            {{ statusConfig[currentOrder.status]?.label }}
          </el-tag>
        </el-form-item>
        <el-form-item label="新状态" prop="newStatus">
          <el-select
              v-model="currentOrder.newStatus"
              placeholder="请选择新状态"
              clearable
          >
            <el-option
                v-for="(item, key) in statusConfig"
                :key="key"
                :label="item.label"
                :value="key"
                :disabled="!isValidStatusChange(currentOrder.status, key)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="statusDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmStatusChange">确认修改</el-button>
      </template>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog
        title="确认删除"
        v-model="deleteDialogVisible"
        width="300px"
        :close-on-click-modal="false"
        destroy-on-close
    >
      <div class="delete-warning-content">
        <el-icon class="warning-icon"><Warning /></el-icon>
        <p>确定要删除ID为 <span class="delete-id">{{ deleteOrderId }}</span> 的订单吗？</p>
        <p class="delete-warning-text">删除后数据将无法恢复，请谨慎操作！</p>
      </div>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确认删除</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Search, Document, User, Shop, DocumentCopy, Clock, Money,
  Edit, Delete, Warning
} from '@element-plus/icons-vue'
import axios from 'axios'

// 查询表单数据
const queryForm = reactive({
  orderId: '',
  realName: '',
  merchantName: ''
})

// 订单列表数据
const orderList = ref([])
// 分页信息
const pagination = reactive({
  pageNo: 1,
  pageSize: 10,
  count: 0,
  totalPage: 0
})

// 状态管理
const loading = ref(false)
const statusDialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const deleteOrderId = ref('')
const currentOrder = ref({ id: '', status: '', newStatus: '' })

// 订单状态配置
const statusConfig = {
  '0': { label: '待取车', type: 'warning' },
  '2': { label: '已取车', type: 'info' },
  '3': { label: '已还车', type: 'primary' },
  '4': { label: '待支付', type: 'purple' },
  '5': { label: '订单完成', type: 'success' }
}

// 页面加载时获取订单列表
onMounted(() => {
  fetchOrderList()
})

// 获取订单列表
const fetchOrderList = async () => {
  loading.value = true
  try {
    const params = {
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
      orderId: queryForm.orderId || undefined,
      realName: queryForm.realName || undefined,
      merchantName: queryForm.merchantName || undefined
    }

    const response = await axios.get('/api/admin/order/pagelist.do', { params })
    if (response.data.success && response.data.code === 200) {
      const data = response.data.data
      orderList.value = data.records || []
      pagination.pageNo = data.pageNo
      pagination.pageSize = data.pageSize
      pagination.count = data.count
      pagination.totalPage = data.totalPage
    } else {
      ElMessage.error(response.data.message || '获取订单列表失败')
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('网络错误，获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 查询处理
const handleQuery = () => {
  pagination.pageNo = 1
  fetchOrderList()
}

// 重置查询
const resetQuery = () => {
  queryForm.orderId = ''
  queryForm.realName = ''
  queryForm.merchantName = ''
  pagination.pageNo = 1
  fetchOrderList()
}

// 分页事件
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.pageNo = 1
  fetchOrderList()
}

const handleCurrentChange = (page) => {
  pagination.pageNo = page
  fetchOrderList()
}

// 状态修改判断
const canEditStatus = (status) => {
  return status !== '5'
}

const isValidStatusChange = (currentStatus, newStatus) => {
  const validTransitions = {
    '0': ['2'],         // 待取车 → 已取车
    '2': ['3'],         // 已取车 → 已还车
    '3': ['4'],         // 已还车 → 待支付
    '4': ['5'],         // 待支付 → 完成
    '5': []             // 完成状态不能修改
  }
  return validTransitions[currentStatus]?.includes(newStatus) || false
}

// 打开状态修改弹窗
const handleEditStatus = (row) => {
  currentOrder.value = {
    id: row.id,
    status: row.status,
    newStatus: ''
  }
  statusDialogVisible.value = true
}

// 确认修改状态
const confirmStatusChange = async () => {
  if (!currentOrder.value.newStatus) {
    ElMessage.warning('请选择新状态')
    return
  }

  try {
    const response = await axios.post('/api/admin/order/updated.do', new URLSearchParams({
      id: currentOrder.value.id,
      status: currentOrder.value.newStatus
    }))

    if (response.data.success) {
      ElMessage.success('订单状态修改成功')
      statusDialogVisible.value = false
      fetchOrderList()
    } else {
      ElMessage.error(response.data.message || '修改失败')
    }
  } catch (error) {
    console.error('修改状态失败:', error)
    ElMessage.error('网络错误，修改失败')
  }
}

// 删除订单
const handleDelete = (id) => {
  deleteOrderId.value = id
  deleteDialogVisible.value = true
}

const confirmDelete = async () => {
  try {
    const response = await axios.post('/api/admin/order/deleted.do', new URLSearchParams({
      id: deleteOrderId.value
    }))

    if (response.data.success) {
      ElMessage.success('订单删除成功')
      deleteDialogVisible.value = false
      fetchOrderList()
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('网络错误，删除失败')
  }
}
</script>

<style scoped>
.order-management-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
  padding-bottom: 12px;
  border-bottom: 1px solid #eee;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 查询表单 */
.query-form-card {
  margin-bottom: 24px;
  border-radius: 8px;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  overflow: hidden;
}

.query-form {
  padding: 16px 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.query-input {
  width: 200px;
}

.query-btn {
  margin-right: 8px;
}

/* 订单卡片容器 */
.order-cards-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(720px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

/* 订单卡片 */
.order-card {
  border-radius: 10px;
  overflow: hidden;
  transition: all 0.3s ease;
  border: none;
  background-color: #fff;
}

.order-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 20px rgba(0, 0, 0, 0.08);
}

/* 订单头部 */
.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #f0f0f0;
}

.order-id {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #666;
  gap: 6px;
}

.id-icon {
  color: #409eff;
  font-size: 16px;
}

.id-value {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.order-status {
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 13px;
  font-weight: 500;
}

/* 订单内容 */
.order-content {
  padding: 20px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.info-card {
  background-color: #fafafa;
  border-radius: 6px;
  padding: 14px;
  transition: all 0.2s ease;
}

.info-card:hover {
  background-color: #f5f7fa;
}

.info-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

.info-icon {
  color: #409eff;
  font-size: 18px;
}

.info-title {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.info-detail {
  font-size: 13px;
  color: #666;
  line-height: 1.8;
}

.detail-item {
  padding: 2px 0;
}

/* 金额样式 */
.final-amount-item {
  color: #36d399;
  font-weight: 500;
}

.damage-fee-item {
  color: #f87272;
}

.overtime-fee-item {
  color: #fbbd23;
}

.final-amount, .damage-fee, .overtime-fee {
  font-weight: 500;
}

/* 订单操作区 */
.order-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 14px 20px;
  border-top: 1px solid #f0f0f0;
  background-color: #f8f9fa;
}

.btn-icon {
  margin-right: 4px;
  font-size: 14px;
}

.edit-btn, .delete-btn {
  padding: 6px 14px;
  border-radius: 4px;
  font-size: 13px;
}

/* 空状态和骨架屏 */
.empty-state {
  grid-column: 1 / -1;
  padding: 80px 0;
}

.order-skeleton {
  grid-column: 1 / -1;
  padding: 20px;
}

/* 分页 */
.pagination-container {
  text-align: right;
  padding: 10px 0;
}

.pagination {
  --el-pagination-font-size: 13px;
  --el-pagination-item-size: 30px;
}

/* 弹窗样式 */
.status-form {
  margin-top: 10px;
}

.delete-warning-content {
  padding: 10px 0;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.warning-icon {
  color: #f59e0b;
  font-size: 24px;
  margin-bottom: 8px;
}

.delete-id {
  color: #f56c6c;
  font-weight: 500;
}

.delete-warning-text {
  color: #f56c6c;
  font-size: 13px;
  margin-top: 4px;
}

/* 响应式调整 */
@media (max-width: 1500px) {
  .order-cards-container {
    grid-template-columns: repeat(auto-fill, minmax(600px, 1fr));
  }
}

@media (max-width: 1200px) {
  .info-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .amount-info {
    grid-column: span 2;
  }
}

@media (max-width: 768px) {
  .order-cards-container {
    grid-template-columns: 1fr;
  }

  .info-grid {
    grid-template-columns: 1fr;
  }

  .amount-info {
    grid-column: span 1;
  }

  .query-input {
    width: 100%;
  }

  .query-form {
    gap: 12px;
  }

  .el-form-item {
    width: 100%;
    margin-bottom: 8px;
  }

  .order-actions {
    justify-content: center;
    flex-wrap: wrap;
  }

  .order-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .order-status {
    align-self: flex-end;
    margin-top: -24px;
  }
}

@media (max-width: 480px) {
  .order-management-container {
    padding: 12px;
  }

  .order-content {
    padding: 12px;
  }

  .info-card {
    padding: 10px;
  }
}
</style>